package mysqlxa;

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.UUID;

/**
 * @Author: admin
 * @Description:
 * @Date: 2018/10/9 9:00
 */

public class TestXa {
    public void xaSuccess(boolean ep1, boolean ep2) throws SQLException {
        String xaId = UUID.randomUUID().toString().replace("-", "");
        Connection c1 = null;
        Connection c2 = null;
        Statement s1 = null;
        Statement s2 = null;
        try {
            c1 = ConnectionFactory.getConnection("192.168.0.27", "test", "root", "123456", 3306);
            c2 = ConnectionFactory.getConnection("192.168.0.201", "lyl", "root", "qj12345678@", 3316);
            //          s1.executeUpdate()
            s1 = c1.createStatement();
            s2 = c2.createStatement();
            s1.execute("XA START '" + xaId + "'");
            s2.execute("XA START '" + xaId + "'");

            boolean r1= s1.execute("UPDATE `account` SET `money` = `money` - 300 WHERE `id`=1");
            int count1=s1.getUpdateCount();
            boolean r2= s2.execute("UPDATE `account` SET `money` = `money` + 300 WHERE `id`=1");
            int count2=s2.getUpdateCount();
            System.out.println(count1);
            System.out.println(count2);
            System.out.println(r1);
            System.out.println(r2);
            s1.execute("XA END " + "'" + xaId + "'");
            s1.execute("XA PREPARE " + "'" + xaId + "'");

            s2.execute("XA END " + "'" + xaId + "'");
            s2.execute("XA PREPARE " + "'" + xaId + "'");

            if (ep1) {
                throw new RuntimeException("事务回滚1");
            }


            if (ep2) {
                throw new RuntimeException("事务回滚2");
            }
            s1.execute("XA COMMIT " + "'" + xaId + "'");
            s2.execute("XA COMMIT " + "'" + xaId + "'");

        } catch (Exception e) {
            e.printStackTrace();
            if (s1 != null) {
                s1.execute("XA ROLLBACK " + "'" + xaId + "'");
            }
            if (s2 != null) {
                s2.execute("XA ROLLBACK " + "'" + xaId + "'");
            }

        } finally {
            if (c1 != null) {
                try {
                    c1.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (c2 != null) {
                try {
                    c2.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }

    }
}
